<template>
  <!-- 屏幕表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="1000px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="100"
      >
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="屏幕编号" prop="screenCode">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.screenCode"
                  placeholder="请输入屏幕编号"
                  clearable
                  style="width: 240px"
                />
                <span v-else>{{ formData.screenCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="屏幕名称" prop="screenName">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.screenName"
                  placeholder="请输入屏幕名称"
                  clearable
                  style="width: 240px"
                />
                <span v-else>{{ formData.screenName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="屏幕类型" prop="screenType">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.screenType"
                  placeholder="请输入屏幕类型"
                  clearable
                  style="width: 240px"
                />
                <span v-else>{{ formData.screenType }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="位置描述" prop="positionDescription">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.positionDescription"
                  placeholder="请输入位置描述"
                  clearable
                  style="width: 240px"
                />
                <span v-else>{{ formData.positionDescription }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作中心" prop="workshopName">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="workCenterList"
                  placeholder="请输入工作中心"
                  clearable
                  style="width: 240px"
                  @change="changeWorkCenter"
                  filterable
                  multiple
                >
                  <el-option
                    v-for="item in workCenters"
                    :key="item.id"
                    :label="`${item.workshopCode}-${item.workshopName}`"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ formData.workshopName }}</span>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="物料" prop="materialName">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="materialList"
                  placeholder="请输入物料"
                  clearable
                  style="width: 240px"
                  @change="changeMaterial"
                  filterable
                  multiple
                >
                  <el-option
                    v-for="item in materials"
                    :key="item.id"
                    :label="`${item.materialCode}-${item.materialName}`"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ formData.materialName }}</span>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="物料" prop="materialId">
                <select-contenttwo-input
                  v-if="!props.isReadonly"
                  style="width: 240px"
                  :isMultiple="true"
                  :showSelectDevice="formData.materialList"
                  :plantId="formData.plantId"
                  :disabled="formData.plantId === ''"
                  filterable
                  clearable
                  @get-device="(id, object) => getDevice(id, object, $index)"
                />
                <span v-else>
                  <!-- 提取并显示 materialName -->
                  {{ getMaterialNames(formData.materialList) }}
                </span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
        <el-card shadow="never" class="table-container">
          <template #header v-if="!props.isReadonly">
            <el-button type="success" plain @click="handleAdd">
              <i-ep-plus />
              新增</el-button
            >
          </template>
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="60"
              />
              <el-table-column
                label="看板名称"
                props="spectacularsName"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.spectacularsName'"
                    :rules="rules.sonspectacularsName"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.spectacularsId"
                      placeholder="请选择看板"
                      clearable
                      filterable
                      @change="changeSpectaculars($index, row.spectacularsId)"
                    >
                      <el-option
                        v-for="item in spectacularsList"
                        :key="item.id"
                        :label="`${item.spectacularsName}`"
                        :value="item.id"
                      />
                    </el-select>
                    <span v-else>{{ row.spectacularsName }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="顺序号"
                props="sequenceCode"
                min-width="140"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.sequenceCode'"
                    :rules="rules.sonsequenceCode"
                    label-width="0"
                  >
                    <el-input-number
                      v-if="!props.isReadonly"
                      v-model="row.sequenceCode"
                      placeholder="请输入顺序号"
                      clearable
                      style="width: 120px"
                      :min="0"
                    />
                    <span v-else>{{ row.sequenceCode }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="切换时间/秒"
                props="switchingTime"
                min-width="130"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.switchingTime'"
                    :rules="rules.sonswitchingTime"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.switchingTime"
                      placeholder="请输入切换时间"
                      clearable
                    />
                    <span v-else>{{ row.switchingTime }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="刷新频率/秒"
                props="refreshRate"
                min-width="100"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.refreshRate'"
                    :rules="rules.sonrefreshRate"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.refreshRate"
                      disabled
                      clearable
                    />
                    <span v-else>{{ row.refreshRate }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="看板描述"
                props="spectacularsDescription"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.spectacularsDescription'"
                    :rules="rules.sonspectacularsDescription"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.spectacularsDescription"
                      clearable
                      disabled
                    />
                    <span v-else>{{ row.spectacularsDescription }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="100"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESSCREENADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    formData.materialList = [];
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  screenCode: "",
  screenName: "",
  screenType: "",
  positionDescription: "",
  workshopId: "",
  workshopCode: "",
  workshopName: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  remarks: "",
  version: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  materialList: [],
  enabled: "",
  deleted: "",
  details: [
    {
      id: "",
      screenId: "",
      spectacularsId: "",
      spectacularsName: "",
      spectacularsDescription: "",
      refreshRate: "",
      sequenceCode: 0,
      remarks: "",
      version: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  screenCode: [
    { required: true, message: "请输入看板编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  screenName: [
    { required: true, message: "请输入看板名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  screenType: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  positionDescription: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  workshopName: [
    { required: true, message: "请选择工作中心", trigger: "clear" },
  ],
  materialName: [{ required: true, message: "请输入物料", trigger: "clear" }],
  sonspectacularsName: [
    { required: true, message: "请输入物料", trigger: "clear" },
  ],
  sonspectacularsDescription: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sonrefreshRate: [],
  sonsequenceCode: [],
  sonswitchingTime: [
    { required: true, message: "请输入切换时间", trigger: "blur" },
    { pattern: /^[0-9]*$/, message: "请输入数字", trigger: "blur" },
  ],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  screenId: "",
  spectacularsId: "",
  spectacularsName: "",
  spectacularsDescription: "",
  refreshRate: "",
  sequenceCode: 0,
  switchingTime: "",
  remarks: "",
  version: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
        materialList.value = newVal.materialId.split(",");
        workCenterList.value = newVal.workshopId.split(",");
        formData.materialList = [
          {
            id: newVal.materialId,
            materialName: newVal.materialName,
            materialCode: newVal.materialCode,
            unit: newVal.baseQuantityUnit,
          },
        ];
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}
function getMaterialNames(materialList) {
  // 如果 materialList 是数组且不为空
  if (Array.isArray(materialList) && materialList.length > 0) {
    // 假设 materialList 是一个包含物料信息的对象数组，提取 materialName 并拼接
    const materialNames = materialList
      .map((item) => item.materialName)
      .join(", ");
    return materialNames;
  }
  // 如果 materialList 为空或非数组，则返回空字符串
  return "";
}
// 获取选中的数据进行回显并赋值
function getDevice(Ids: string[], Objects: any[], index: number) {
  // 输出第一个物料对象，用于调试
  console.log(Objects[0]);

  // 初始化数组，用于存储多个物料的属性
  let materialCodes = [];
  let materialNames = [];
  let unit = "";

  // 遍历所有物料对象，拼接物料代码、名称，并处理单位（假设单位相同）
  Objects.forEach((obj) => {
    materialCodes.push(obj.materialCode);
    materialNames.push(obj.materialName);
    unit = obj.unit; // 这里假设所有物料的单位相同
  });

  // 更新 formData 对象中的属性，使用逗号连接多个物料信息
  formData.materialId = Ids.join(",");
  formData.materialCode = materialCodes.join(",");
  formData.materialName = materialNames.join(",");
  formData.baseQuantityUnit = unit;

  // 输出更新后的 formData.materialId，用于调试
  console.log(formData.materialId);
}
/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.screenCode = "";
  formData.screenName = "";
  formData.screenType = "";
  formData.positionDescription = "";
  formData.workshopId = "";
  formData.workshopCode = "";
  formData.workshopName = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.remarks = "";
  formData.version = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  materialList.value = [];
  workCenterList.value = [];
  formData.materialList = [
    {
      id: "",
      materialName: "",
      materialCode: "",
      unit: "",
    },
  ];
}

const loading = ref(false);

/** 屏幕保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/mes/messcreen/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/mes/messcreen/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}
onMounted(() => {
  getWorkCenters();
  getMaterials();
  getSpectaculars();
});

//工作中心
const workCenters = ref([]);
async function getWorkCenters() {
  await request({
    url: "mes/mesworkshop/getList",
    method: "post",
    data: { enabled: 1 },
  }).then((res) => {
    workCenters.value = res.data;
  });
}
//工作中心赋值
const workCenterList = ref([]);
const changeWorkCenter = (id: any) => {
  formData.workshopId = workCenterList.value.join(",");
  let materialCodeList = [];
  let materialNameList = [];
  workCenterList.value.forEach((item: any) => {
    workCenters.value.forEach((i) => {
      if (item === i.id) {
        materialCodeList.push(i.workshopCode);
        materialNameList.push(i.workshopName);
      }
    });
  });
  formData.workshopCode = materialCodeList.join(",");
  formData.workshopName = materialNameList.join(",");
};
const changeMaterial = (e: any) => {
  formData.materialId = materialList.value.join(",");
  let materialCodeList = [];
  let materialNameList = [];
  materialList.value.forEach((item: any) => {
    materials.value.forEach((i) => {
      if (item === i.id) {
        materialCodeList.push(i.materialCode);
        materialNameList.push(i.materialName);
      }
    });
  });
  formData.materialCode = materialCodeList.join(",");
  formData.materialName = materialNameList.join(",");
};

//物料
const materials = ref([]);
const materialList = ref([]);
async function getMaterials() {
  await request({
    url: "mdm/mdmmaterial/getList",
    method: "post",
    data: { enabled: 1 },
  }).then((res) => {
    materials.value = res.data;
  });
}
//看板
const spectacularsList = ref([]);
async function getSpectaculars() {
  await request({
    url: "mes/messpectaculars/getList",
    method: "post",
    data: {},
  }).then((res) => {
    spectacularsList.value = res.data;
  });
}
//看板赋值
const changeSpectaculars = (index: number, id: any) => {
  if (!id) {
    formData.details[index].spectacularsName = "";
    formData.details[index].refreshRate = "";
    formData.details[index].spectacularsDescription = "";
  }
  spectacularsList.value.forEach((item: any) => {
    //物料为空是清除信息
    if (item.id === id) {
      formData.details[index].spectacularsName = item.spectacularsName;
      formData.details[index].refreshRate = item.refreshRate;
      formData.details[index].spectacularsDescription =
        item.spectacularsDescription;
    }
  });
};
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}
:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
</style>
